package main

import (
	"acs/dispatcher"
	"flag"
	"fmt"
	"net/http"
	_ "net/http/pprof"
	"os"
	"rpc-go/server/config"
	"rpc-go/server/service"
	"rpc-go/server/service/register"
	"rpc-go/server/transport"

	"github.com/BurntSushi/toml"
)

var (
	monitor *dispatcher.Monitor
)

func main() {
	//载入rpc配置文件。默认地址在conf/config.toml
	var rpcconfigFile string
	flag.StringVar(&rpcconfigFile, "rpc", "./conf/rpcconfig.toml", " set rpc config file path")
	var configFile string
	flag.StringVar(&configFile, "conf", "./conf/config.toml", " set config file path")
	flag.Parse()
	dispatcher.Conf = new(dispatcher.Config)
	if _, err := toml.DecodeFile(configFile, dispatcher.Conf); err != nil {
		panic(err)
	}
	flag.Parse()
	conf, err := config.LoadConfig(rpcconfigFile)
	if err != nil {
		config.Logger.Error("load Config Error:", err.Error())
		os.Exit(1)
	}
	defer config.Logger.Flush()
	monitor, err = dispatcher.NewMonitor(dispatcher.Conf.EventBrokerEndpoints, dispatcher.Conf.EventBrokerAuthinfo, dispatcher.Conf.NodesMonitorDir)
	if err != nil {
		panic(err)
	}
	go monitor.Start()
	srvs := service.NewService(conf)
	register.RegisterHandler("acsdispatcher.serveraddr", serveraddrHandler)
	go srvs.Run()

	go func() {
		http.ListenAndServe("localhost:6060", nil)
	}()
	signalChan := dispatcher.InitSignal()
	dispatcher.HandleSignal(signalChan)
}

func serveraddrHandler(conn *transport.JumeiConn, request interface{}) (response string, err error) {
	node := monitor.GetLastSuggestedNodeAddr()
	status := 0
	if node == "" {
		status = 1
		node = "no node to use."
	}
	response = fmt.Sprintf(`{"s": %v, "m":"%v"}`, status, node)
	config.Logger.Infof("acsdispatcher.serveraddr : %s", response)
	return
}
